<?php
namespace App\Common\Cla\ClaBase\Traits;

use App\Common as com;

trait GoStaticPool {

	private static $_gosPool = [];

	private static $_gosPoolOfParam = [];

	private static $_gosPoolOfUnique = [];

	/**
	 * 获取池
	 * @param string $poolName 池名
	 * @param \Closure $callback 回调
	 * @return mixed
	 */
	protected static function gosPool( string $poolName, \Closure $callback ){
		if( ! isset( self::$_gosPool[ $poolName ] ) ){
			self::$_gosPool[ $poolName ] = $callback();
		}
		//
		return self::$_gosPool[ $poolName ];
	}

	/**
	 * 获取池(参数唯一，相同参数确认唯一)
	 * @param string $poolName 池名
	 * @param int|string|array $paramMixed 池参数
	 * @param \Closure $callback 回调
	 * @return mixed
	 */
	protected static function gosPoolParam( string $poolName, $paramMixed, \Closure $callback ) {
		$paramMixedStr = is_array( $paramMixed ) ? implode( '_', $paramMixed ) : $paramMixed;
		$poolQuote = &self::$_gosPoolOfUnique[ $poolName ][ $paramMixedStr ];
		// 检查是否存在 || 检查参数是否一致
		if( ! isset( $poolQuote )){
			$poolQuote = $callback();
		}
		//
		return $poolQuote;
	}

	/**
	 * 获取池(poolName唯一，poolName确认唯一，参数不同时自动销毁上一次的数据)
	 * @param string $poolName 池名
	 * @param int|string|array $paramMixed 池参数 [array]支持一维数组
	 * @param \Closure $callback 回调
	 * @return mixed
	 */
	protected static function gosPoolUnique( string $poolName, $paramMixed, \Closure $callback ) {
		// ...
		if( is_array( $paramMixed ) ){
			$paramMixedStr = implode( '_', $paramMixed );
		}else if( is_string( $paramMixed ) || is_numeric( $paramMixed ) ){
			$paramMixedStr = $paramMixed;
		}else{
			throw com\Lib\Err\Exception::makeOfNew( '$paramMixed 参数类型错误', com\Lib\Err\Code::$sysFunParamError );
			return null;
		}
		//
		$poolQuote = &self::$_gosPoolOfUnique[ $poolName ];
		// 检查是否存在 || 检查参数是否一致
		if( ! isset( $poolQuote ) || $poolQuote['paramMixedStr'] != $paramMixedStr ){
			$poolQuote['paramMixedStr'] = $paramMixedStr;
			$poolQuote['data'] = $callback();
		}
		//
		return $poolQuote['data'];
	}
	
}
